<?php
/**
 * CreateDatabaseTest test case.
 */
class Entidade_Model_ConexaoDB extends Zend_Db_Adapter_Sqlsrv
{

  private $sgbd;
  /**
   * A conexão
   *
   * @var PDO
   */
  private $_conn;

  /**
   *
   * @var array endereços dos arquivos para criação do banco de dados
   */
  private $_fileCreate = array();

  /**
   *
   * @var array endereços dos arquivos para carga no banco de dados
   */
  private $_fileCarga = array();

  /**
   * Endereço do arquivo de configuração
   *
   * @var string
   */
  private $_arqConfiguracao;

  /**
   * Constructs the test case.
   */
  public function __construct ( $sgbd )
  {
    $this->sgbd = $sgbd;
    $this->_arqConfiguracao = APPLICATION_PATH . '/modules/entidade/config.ini';
    $this->_setConexao();
  }

  /**
   * Seta a conexao
   *
   * @param  $dbSchema
   */
  protected function _setConexao ()
  {
    try {

      if (!$this->_conn) {
      
        $config = new Zend_Config_Ini($this->_arqConfiguracao, APPLICATION_ENV, TRUE);
        Zend_Registry::getInstance()->set('config', $config);

        $dsn = Zend_Registry::get('config')->db->adapter . ':host=' . Zend_Registry::get('config')->db->host . ";dbname=" . Zend_Registry::get('config')->db->dbname;
        $userName = Zend_Registry::get('config')->db->username;
        $password = Zend_Registry::get('config')->db->password;
        
        $this->_conn = new PDO($dsn, $userName, $password);
      }

    } catch (PDOException $e) {

      echo $e->getMessage();
      exit();
    }
  }

  public function getListaColuna( $noTabela ){
    
    if( $this->sgbd == 'sqlserver' ){
      
      return $this->getColunaSqlServer( $noTabela );
    }elseif( $this->sgbd == 'sqlserver' ){
      
      return $this->getColunaPostgreSQL( $noTabela );
    }
    
  }
  
  public function getColunaSqlServer( $noTabela ){
    
    $sql = "SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE
                FROM INFORMATION_SCHEMA.COLUMNS
                WHERE TABLE_NAME = '" . $noTabela . "'
                ORDER BY TABLE_NAME, ORDINAL_POSITION";
    
    return $this->_conn->query($sql)->fetchAll();
    
  }
  
  public function getColunaPostgreSQL(){
    
  }

  public function getPkColuna( $noTabela ){
    
    if( $this->sgbd == 'sqlserver' ){
      
      $sql = "sp_pkeys " . $noTabela;
      return $this->_conn->query($sql)->fetchAll();
    }elseif( $this->sgbd == 'pgsql' ){
      
    }
      
  }

  /**
   *
   * @param array $files => Array com os endereços dos arquivos que serão executados
   * @param string $metodoTratamento => Método que tratará os dados do script
   */
  protected function executeQuery ($files, $metodoTratamento)
  {
    try {

      if (! empty($files)) {
        
        foreach ($files as $dbShema => $file) {

          $this->_setConexao($dbShema);
          $query = $this->$metodoTratamento($this->abrirArquivo($file));

          if ($query) {
            
            foreach ($query as $sql) {
              
              if (trim($sql)) {

                $this->_conn->query($sql)->execute();
              }
            }
          }
        }
      }

    } catch (Exception $e) {

      echo $e->getMessage();
      exit();
    }
  }

  /**
   *
   * @param file
   */
  protected function abrirArquivo ($file)
  {

    if (file_exists($file)) {

      $fileOpen = fopen($file, 'r') or die("Falha ao carregar o arquivo: {$file}");
      $data = fread($fileOpen, filesize($file));
      fclose($fileOpen);

      $data = str_replace(array(
        "\r\n",
        "\r",
        "\n"
      ), "\n", $data);
      return $data;

    } else {

      throw new Exception("Não existe o arquivo.");
    }
  }
}